<template>
  <div>
    <!-- 索赔结算发票查询 -->
    <TopFilter ref="TopFilterss" :list="topFilterInit" :cols="3" :collapse="collapse" labelWidth="110" @filterChange="changeHandle" @resetChange="resetHandle"></TopFilter>
    <FilterTable
      ref="table"
      :columns="columns"
      :params="fetchParams"
      :fetchapi="fetchapi"
      :datakey="'records'"
      :onColumnsChange="columns => (this.columns = columns)"
      
      selectionType="single"
    >
      <template slot="controls" slot-scope="props">
        <el-button size="small" type="primary"   @click="claimExportData">导出</el-button>
      </template>
    </FilterTable>

    <!--  服务中心选择 -->
    <BaseDialog :visible.sync="selectDelearFlag" title="服务中心选择" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <DealerList @close="Delearclose" @save="Delearsave" selectionType="multiple" />
    </BaseDialog>

  </div>
</template>
<script>
import moment from "moment";  
import { exportExcelFile } from '@/utils/index';
import { getAppId } from '@/assets/js/auth';
import { dictionary } from '@/utils/dictMixin';
import { queryClaimStatementReport,getPartType,claimStatementReportForExport} from '@/api/claim/factory/ClaimStatementQueryFactory';
import { troubleDesc } from '../../../../api/repair/precontract/precontractStatus';
import DealerList from '@/pages/claimDemage/tools/DealerList.vue';
import { getRegion, getLevelOneArea, getLevelTwoAndThreeArea } from '@/api/cms-common/dealerdata/index'; //事业部，办事处
// mock 方法 
//import mockFun from "@/mock/fun"
//const { mockList } = mockFun.ClaimStatementQueryDealer.mockFunWrap()// 涉及闭包 所以需要先调用外层函数一次 然后通过解构获取对应mock方法
import {getModelAll} from '@/api/cms-common/basedata';
export default {
  name:"claimStatementInvoiceQuery",
  mixins: [dictionary],
  components: {
    DealerList
  },
  data() {
    return {
      dataList: [],
      visibleDrawer: false,
      collapse: true,
      infoId: null,
      fetchapi: queryClaimStatementReport ,//getClaimAccountInfo,
      topFilterInit: this.topFilterInitFun(),
      flterValue: {}, //参数
      rowData: {},
      dataType:'',
      columns: this.creatHeader(),
      fetchParams: {xhrAbort: false,
      beginSettleDate:moment().startOf('month').format('YYYY-MM'),
      endSettleDate:moment().endOf('month').format('YYYY-MM')
      }, //ipa 接口
      selectedRows: [], 
      dialogTitle: '',
      visibleAdd: false,
      signInvoices: false,
      selectDelearFlag: false,
      selectDealerData: [],
      dealerData: [],
	  dealerCompanyCode: [],
      
      ORG_TYPE_SERVICE_WAR_AREA: 15061019, //服务战区
      ORG_TYPE_SERVICE_BIG_AREA: 15061020, //服务大区
      ORG_TYPE_SERVICE_SMALL_AREA: 15061021, //服务小区
    };
  },
  created() {
  
    //this.chuqi();
  },
   mounted() {
    this.getTopLevelArea(this.ORG_TYPE_SERVICE_WAR_AREA, 'warAreaCode');
  },
  methods: {
    
    //搜索获取数据
    changeHandle(val) {
      this.fetchParams = Object.assign({}, this.fetchParams, val, { dealerCode: this.searchDealerCode, dealerCompanyCode: this.selectDealerData.length ? this.selectDealerData : null });
      console.log(val);
    },
    resetHandle(val) {
      this.dealerData = [];
      this.selectDealerData = [];
      this.fetchParams = Object.assign({}, this.fetchParams, val, { dealerCompanyCode: null }, { xhrAbort: false });
    },
    // 索赔结算单导出
    async claimExportData() {
      await claimStatementReportForExport(this.fetchParams).then(res => {
        console.log(res);
        exportExcelFile(res.data, '索赔结算统计导出');
      });
    },
    Delearclose() {
      this.selectDelearFlag = false;
    },
    //服务中心选择保存
    Delearsave(obj) {
      console.log('选择数据传递', obj);
      this.dealerData = obj;
      this.selectDealerData = [];
      obj.forEach((item) => {
        this.selectDealerData.push(item.dealerCompanyCode);
      });
      this.selectDelearFlag = false;
    },
	//获取所有车型
    async getModel() {
      let res = await getModelAll();
      if (res.resultCode === 200) {
        this.topFilterInit.find(item => item.fieldName === 'modelCode').itemList = res.data.map(x => ({text:x.modelName,value:x.modelCode}));

      }
    },
     //获取大区
    async getBigArea() {
      const res = await getRegion();
      if (res.resultCode === 200) {
        this.topFilterInit.find((item) => item.fieldName === 'bigAreaCode').itemList = res.data.map((x) => ({ value: parseInt(x.id), text: x.orgName }));
      }
    },
    //获取顶层组织数据
    async getTopLevelArea(areaType, filedName) {
      const res = await getLevelOneArea(areaType);
      if (res.resultCode === 200) {
        this.topFilterInit.find((item) => item.fieldName === filedName).itemList = res.data.map((x) => ({ value: parseInt(x.id), text: x.orgName }));
      }
    },
    //顶层和中层组织数据修改
    async changeTopAndMiddleLevelArea(deptId, sonAreaType, parentFieldName, sonFieldName, smallFieldName, flag = true) {
      let sonArea = this.topFilterInit.find((item) => item.fieldName === sonFieldName);
      let smallArea = this.topFilterInit.find((item) => item.fieldName === smallFieldName);
      if (!deptId) {
        sonArea.initialValue = '';
        sonArea.itemList = [];
        smallArea.initialValue = '';
        smallArea.itemList = [];
      } else {
        if (flag) {
          //正常的级联，清空原来选择的数据
          sonArea.initialValue = '';
          smallArea.initialValue = '';
        }
        const res = await getLevelTwoAndThreeArea(sonAreaType, deptId);
        if (res.resultCode === 200) {
          sonArea.itemList = res.data.map((x) => ({ value: parseInt(x.id), text: x.orgName }));
        }
      }
    },
    //搜索数据
    topFilterInitFun() {
      return [
        {
          type: 'SELECT',
          label: '服务战区',
          fieldName: 'warAreaCode',
          placeholder: '请选择',
          initialValue: '',
          itemList: [],
          change: (val) => {
            console.log('val',val)
            this.changeTopAndMiddleLevelArea(val, this.ORG_TYPE_SERVICE_BIG_AREA, 'warAreaCode', 'bigAreaCode', 'smallAreaCode');
          },
        },
        {
          type: 'SELECT',
          label: '服务大区',
          fieldName: 'bigAreaCode',
          placeholder: '请选择',
          initialValue: '',
          itemList: [],
          change: (val) => {
            this.changeTopAndMiddleLevelArea(val, this.ORG_TYPE_SERVICE_SMALL_AREA, 'bigAreaCode', 'smallAreaCode', 'smallAreaCode');
          },
        },
        {
          type: 'SELECT',
          label: '服务小区',
          fieldName: 'smallAreaCode',
          placeholder: '请选择',
          initialValue: '',
          itemList: [],
        },
        {
          type: 'INPUT',
          label: '服务中心',
          render: (p) => {
            return (
              <div>
                <el-select v-model={this.selectDealerData} disabled={true} multiple placeholder="请选择">
                  {this.dealerData.map((item) => (
                    <el-option key={item.dealerCode} label={item.dealerShortname} value={item.dealerCompanyCode} />
                  ))}
                </el-select>
                <multiuse-button style="position: absolute;right: 0;height:100%" icon="el-icon-search" onClick={() => (this.selectDelearFlag = true)} />
              </div>
            );
          },
        },
		{
          type: 'RANGE_DATE',
          label: '结算月份',
          fieldName: 'beginSettleDate|endSettleDate',
          placeholder: '请输入',
          dateType:'monthrange',
          initialValue: [
            moment(new Date()).subtract(1,'months')
              .format("YYYY-MM"),
            moment(new Date())
              .format("YYYY-MM")
          ],
          rules: [{ required: true, message: '请选择日期', trigger: 'change' }]
        },
        { type: 'SELECT', label: '车型', fieldName: 'modelCode', placeholder: '请选择', initialValue: '', itemList: this.getModel() },
        ];
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          fixed: 'left',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        
        { title: '服务中心代码', dataIndex: 'dealerCode' },
        { title: '服务中心简称', dataIndex: 'dealerName' },                       
        { title: '服务战区', dataIndex: 'warAreaName',  showOverflowTooltip: true},
        { title: '服务大区', dataIndex: 'bigAreaName' },
        { title: '服务小区', dataIndex: 'smallAreaName' },
        { title: '车型', dataIndex: 'modelName'},
        { title: '结算月份', dataIndex: 'settleDate', sorter: true },
        // { title: '结算单类型', dataIndex: 'finalStatementType', sorter: true },
        { title: '索赔单数', dataIndex: 'claimCount'},
        { title: '工时费', dataIndex: 'labourAmount', sorter: true,precision: 2 },
        { title: '材料费', dataIndex: 'partAmount', sorter: true ,precision: 2},
        { title: '管理费', dataIndex: 'partManageAmount', sorter: true,precision: 2 },
        { title: '外出服务费', dataIndex: 'helpAmount', sorter: true,precision: 2 },
        { title: '其他费用', dataIndex: 'addAmount', sorter: true,precision: 2 },
        { title: '技术活动', dataIndex: 'techcinelAmount', sorter: true,precision: 2 },
        { title: '误判金额', dataIndex: 'cbAmount', sorter: true,precision: 2 },
        { title: '服务活动', dataIndex: 'activityAmount', sorter: true,precision: 2 },
        { title: 'PDI费', dataIndex: 'pdiCount', sorter: true,precision: 2 },
        { title: '首次保养', dataIndex: 'firstMaintenanceCount', sorter: true,precision: 2 },
        { title: '善意索赔', dataIndex: 'goodWillClaimCount', sorter: true,precision: 2 },
        { title: '激励费用', dataIndex: 'inventiveAmount', sorter: true,precision: 2 },
        { title: '运费', dataIndex: 'freightAmount', sorter: true,precision: 2 },
        { title: '合计', dataIndex: 'sumAmount', sorter: true,precision: 2 },
        { title: '备注', dataIndex: '', sorter: true },
      ];
    }
  }
};
</script>

<style lang="less" scoped></style>
